#include "ImageColorBar.h"
#include <algorithm/shared/tool/imageSaver/ImageSaver.h>

#include <QMap>
#include <QPainter>

using namespace solar;

ImageColorBar::ImageColorBar(QQuickItem* parent)
    : QQuickPaintedItem(parent), visible_(false), tick_num_(10), min_tick_(0), max_tick_(300),
      font_size_(8), bar_width_(10), bar_height_(100), offset_(0)
{
    this->update();
}

void ImageColorBar::paint(QPainter* painter)
{
    qDebug() << "image colorbar painting!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
    if (painter == nullptr)
    {
        return;
    }
    if (!visible_)
    {
        qDebug() << "---- visible = " << visible_;
        return;
    }

    // -----------bar----------
    for (int i = 0; i < bar_height_; i++)
    {
        QRect rect(0, bar_height_ - i + offset_, bar_width_, 1);
        auto color = getColor(i, 0, bar_height_);
        painter->fillRect(rect, color);
        // qDebug() <<"  colorbar   i = " << i <<"  color = " << color;
    }

    int total_width = 0;
    //---------tick--------------
    for (int i = 0; i < tick_num_; i++)
    {
        QString str_value;
        str_value =
            QString::asprintf("%.2f", min_tick_ + i * (max_tick_ - min_tick_) / (tick_num_ - 1));
        QFont font;
        font.setFamily("Microsoft Yahei");
        font.setPointSize(font_size_);
        QFontMetrics fm(font);
        QRect rec = fm.boundingRect(str_value);

        int text_width = rec.width();
        int text_height = rec.height();
        // std::cout <<" ----------- text_width = " << text_width <<std::endl;
        // std::cout <<" ----------- text_height = " << text_height <<std::endl;
        // qDebug() <<" strValue = " << strValue;
        int tick_height = offset_ + bar_height_ - ((float)bar_height_ / ((float)tick_num_ - 1) * i);
        int bar_tick_dst = 5;
        QRect text_rect(bar_width_ + bar_tick_dst, tick_height - text_height / 2, text_width,
                       text_height);
        total_width = std::max(total_width, bar_width_ + bar_tick_dst + text_width);
        painter->setFont(font);
        painter->drawText(text_rect, str_value);
    }

    setWidth(total_width);
}

auto ImageColorBar::getColor(float val, float min_val, float max_val) -> QColor
{
    rgb8_pixel_t pixel = ImageSaver::colorbar.getColorAtValue(val, min_val, max_val);
    QColor color((int)pixel[0], (int)pixel[1], (int)pixel[2]);
    return color;
}

void ImageColorBar::rePaint() { update(); }
